package com.jinsp.cameralibrary;

import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;

/**
 * Created by luoshuai on 1/5/22
 * <p>
 * 权限申请fragment
 */
public abstract class PermissionFragment extends Fragment {

    private final int PERMISSION_REQUEST_CODE = 100;
    private PermissionErrorCallback permissionErrorCallback;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(getPermissions(), PERMISSION_REQUEST_CODE);
        } else {
            onPermissionGrantSuccess();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            int sum = grantResults.length;
            for (int i = 0; i < sum; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permissions[i])) {
                        if (permissionErrorCallback != null) {
                            permissionErrorCallback.permissionGrantDenied(permissions[i]);
                        }
                    } else {
                        if (permissionErrorCallback != null) {
                            permissionErrorCallback.permissionGrantFailed(permissions[i]);
                        }
                    }
                    return;
                }
            }
            onPermissionGrantSuccess();
        }
    }

    public abstract String[] getPermissions();              //获取权限列表

    public abstract void onPermissionGrantSuccess();        //权限申请成功

    /**
     * 注册权限失败返回结果
     *
     * @param permissionErrorCallback 结果回调
     */
    public void registerPermissionCallback(PermissionErrorCallback permissionErrorCallback) {
        this.permissionErrorCallback = permissionErrorCallback;
    }

    public interface PermissionErrorCallback {

        void permissionGrantDenied(String deniedPermission);

        void permissionGrantFailed(String failedPermission);
    }
}
